package com.example.demo.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserMapper userMapper;
    //登录接口
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){
        //将输入的数据与数据库进行匹配，看是否存在
        User haveUser = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, user.getPassword()));
        if (haveUser == null) {
            return Result.error("-1","用户或密码错误");
        }
        return Result.success();
    }

    //注册接口
    @PostMapping("/register")
    public Result<?> register(@RequestParam("username") String username, @RequestParam("password") String password){
        //将输入的数据与数据库进行匹配，看是否存在
        User haveUser = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if (haveUser != null) {
            return Result.error("-1","用户已经存在");
        }
        //如果不存在，则将该注册号插入进去
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userMapper.insert(user);
        return Result.success();
    }
}
